require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class TurntableRankItem: UIComponentInterface
local RankItem = {};
HelperFunc.SetUIEnv(RankItem)
local this = RankItem;

this._rankMax = 50;
this.ranklist = nil;
this.myObj = nil;
this.buttonTop = nil;
this.timeCtrl = nil;
this.bannerText = nil;
this.timeCount = 0;
this.rewardTimerId = nil;

this.universalRank = nil;
this.headIcon = nil;
this.frameIcon = nil;
this.topCtrl = nil;
this.topRankCtrl = nil;
this.btnHead = nil;
this.universalRankReward = nil;
this.topScore = nil;
this.activityId = 19001;

function RankItem.ReqRankList(rankType, challengeTimeCountDown)
    ---@type ResTurntableRankListInfoMessage
    this.serverRankInfo = logicMgr.ActiveManager.GetTurntableRankInfo(this.activityId,rankType)
    local version = -1
    if this.serverRankInfo then
        version = this.serverRankInfo.rankVersion
    end
    this.rankType = rankType;
    ActivityHandler.sendReqTurntableRankListInfoMessage(this.activityId,rankType,version)
    this.updateData(rankType, challengeTimeCountDown)
end
function RankItem.initData(id,obj,type, challengeTimeCountDown)
    this.activityId = tonumber(id);
    this._rankMax = 50;
    this.rankType = type
    this.ranklist = obj:GetChild("SocialList");
    this.ranklist.itemRenderer = this.setData;
    this.ranklist:SetVirtual()

    this.myObj = obj:GetChild("MySocial");
    this.buttonTop = obj:GetChild("ButtonTop");
    this.timeCtrl = obj:GetController("Time");
    this.bannerText = obj:GetChild("bannerText");

    this.universalRank = {};
    this.headIcon = {};
    this.frameIcon = {};
    this.topCtrl = {};
    this.topRankCtrl = {};
    this.btnHead = {};
    this.universalRankReward = {};
    this.topScore = {};
    for i = 1, 3 do
        local top = obj:GetChild("TOP"..i);
        table.insert(this.universalRank, top:GetChild("TOP"));
        table.insert(this.topCtrl, top:GetController("Type"));
        table.insert(this.topRankCtrl, top:GetController("rank"));
        table.insert(this.universalRankReward, top:GetChild("itemlist"));
        table.insert(this.topScore, top:GetChild("Point"));
        local head = top:GetChild("Head");
        table.insert(this.btnHead, head);
        table.insert(this.headIcon, head:GetChild("head"):GetChild("HeadIcon"));
        table.insert(this.frameIcon, head:GetChild("frame"));
    end
    ListenEvent(Config.EventType.Fresh_Activity_Turntable_Rank,this.ReceiveRankDataMsg)
    this.timeCount = challengeTimeCountDown;
    this.ReqRankList(type, challengeTimeCountDown);
end

function RankItem.updateData(type, challengeTimeCountDown)
    if challengeTimeCountDown ~= nil then
        if challengeTimeCountDown > 0 then
            this.DestroyRewardTimer();
            this.timeCtrl.selectedIndex = 0;
            this.timeCount = challengeTimeCountDown;
            this.bannerText.text = string.format(getLanguage("RaceRankDes3"), HelperFunc.GetSurpTimeStr(this.timeCount));
            this.rewardTimerId = utimer.timeCall(function()
                this.bannerText.text = string.format(getLanguage("RaceRankDes3"), HelperFunc.GetSurpTimeStr(this.timeCount));
                this.timeCount = this.timeCount - 1;
            end,1000);
        else
            this.timeCtrl.selectedIndex = 1;
        end
    else
        this.timeCtrl.selectedIndex = 1;
    end
    this.subRankTableDataList = {};
    local cfgs = dataTable.getDataTable("t_turntablerankaward")
    for k,v in pairs(cfgs) do
        if v.f_Type == type and v.f_ActivityId == this.activityId then
            table.insert(this.subRankTableDataList,v)
        end
    end
    table.sort(this.subRankTableDataList, function (a, b)
        return a.f_RankId < b.f_RankId;
    end);
    this.UpdateRank();
    this.UpdateMyRank();
end

function RankItem.UpdateRank()
    if this.serverRankInfo then
        this.rankServerDataList = this.serverRankInfo.rankList or {}
    else
        this.rankServerDataList = {}
    end
    --table.sort(this.rankServerDataList, function (a, b)
   --     return a.rank < b.rank;
   -- end);
    local firstCfg = this.subRankTableDataList[1]
    this.buttonTop:RemoveChildrenToPool();
    if firstCfg ~= nil then
        if firstCfg.f_SpecialAward ~= nil and firstCfg.f_SpecialAward ~= "" then
            local specialAward = decodeJsonStrToTabel(firstCfg.f_SpecialAward);
            for i = 1, #specialAward do
                local item = this.buttonTop:AddItemFromPool();
                local rewardItem = logicMgr.CostManager.getItemOrEquipDataByIdAndNum(specialAward[i], 1);
                UIComponentInterface:SetItemAllById(item:GetChild("Mask"):GetChild("ItemIcon"), nil, nil, rewardItem.itemModelId);
                item:GetChild("ItemText").text = getLanguage("RaceRankDes"..(17 + i));
                item.onClick:Clear();
                item.onClick:Add(function()
                    if rewardItem.itemType == EnumConst.ItemTypeEnum.HeroEntity then
                        for k,v in pairs(G.dataTable["t_drop"]) do
                            if tonumber(rewardItem.itemModelId) == tonumber(v.f_DropPoolId) then
                                local heroId = decodeJsonStrToTabel(v.f_Hero);
                                if heroId ~= nil then
                                    showUI(PanelNames.UIDrawAnimation, heroId[1][1], nil, false, function()
                                        closeUI(PanelNames.UIDrawAnimation);
                                    end, nil, true, true);
                                end
                                return
                            end
                        end
                    end
                    if logicMgr.ItemManager.IsEquip(rewardItem["itemModelId"]) then
                        showUI(PanelNames.UIEquipInfo, nil, rewardItem);
                    elseif rewardItem.itemType == EnumConst.ItemTypeEnum.Fragment then
                        showUI(PanelNames.UIDebrisInfo, rewardItem, EnumConst.DebrisInfoType.View)
                    else
                        showUI(PanelNames.UIBagItemInfo, rewardItem);
                    end
                end);
            end
        end
    end

    for i = 1, #this.universalRank do
        local cfg = this.getTableData(i);
        if cfg ~= nil then
            logicMgr.CostManager.RefreshItemList(this.universalRankReward[i], decodeJsonStrToTabel(cfg.f_Award), 3, {isShowBigNum = true});
        end
        local item = this.rankServerDataList[i];
        this.btnHead[i].onClick:Clear();
        this.topRankCtrl[i].selectedIndex = i - 1;
        if item == nil then
            this.universalRank[i].text = getLanguage("BillboardRankNeedPlayer");
            this.topCtrl[i].selectedIndex = 0;
            this.headIcon[i].url = EnumConst.AtlasPath.CommonUI.."icon_hero_kb91";
            this.frameIcon[i].url = "";
            this.topScore[i].text = "";
        else
            this.topCtrl[i].selectedIndex = 1;
            this.universalRank[i].text = item.name;
            this:SetPlayerIcon(this.headIcon[i], item.pic, this.frameIcon[i], item.picFrame);
            this.topScore[i].text = string.format("积分：%d",item.orderVal)
        end
    end
    this.UpdateSubRank();
end

function RankItem.UpdateSubRank()
    this.ranklist.numItems = this._rankMax - 3;
end

function RankItem.setData(index, itemObj)
    index = index + 1;
    this.updateItem(itemObj, this.rankServerDataList[index + 3], this.getTableData(index+3), index+3, index);
end

function RankItem.UpdateMyRank()
    local myRankServerData = {};
    myRankServerData.playerId = logicMgr.HeroManager.GetRoleId();
    myRankServerData.name = logicMgr.HeroManager.GetRoleName();
    myRankServerData.pic = logicMgr.HeroManager.GetRoleHeadID();
    myRankServerData.picFrame = logicMgr.HeroManager.GetRoleHeadFrame();
    myRankServerData.lv = logicMgr.HeroManager.GetRoleLevel();
    myRankServerData.rank = 0;
    myRankServerData.orderVal = 0
    if this.serverRankInfo then
        myRankServerData.rank = math.max(this.serverRankInfo.selfRank,0)
        myRankServerData.orderVal = this.serverRankInfo.selfOrderVal
    end
    local myTableData = nil;
    if myRankServerData.rank > 0 then
        myTableData = this.getTableData(myRankServerData.rank);
    end
    this.updateItem(this.myObj, myRankServerData, myTableData, myRankServerData.rank, myRankServerData.rank, true);
end

function RankItem.updateItem(itemObj, serverData, tableData, rankIndex, index, isMe)
    local typeController = itemObj:GetController("type");
    local rankController = itemObj:GetController("rank");
    local ctrlNoRankController = itemObj:GetController("ctrlNoRank");
    if index > 100 or rankIndex == 0 or serverData == nil then
        ctrlNoRankController.selectedIndex = 0;
    else
        ctrlNoRankController.selectedIndex = 1;
    end
    if isMe then
        typeController.selectedIndex = 1;
    else
        typeController.selectedIndex = 0;
    end
    if tableData ~= nil then
        logicMgr.CostManager.RefreshItemList(itemObj:GetChild("itemlist"), tableData.f_Award, 3);
    end
    typeController.selectedIndex = 0;
    local head = itemObj:GetChild("head");
    head.onClick:Clear();
    local rank = rankIndex;
    if serverData ~= nil then
        itemObj:GetChild("name").text = serverData.name;
        itemObj:GetChild("level").text = getLanguage("Sys_HeroLevel")..serverData.lv;
        itemObj:GetChild("point").text = string.format("积分：%d",serverData.orderVal)
        UIComponentInterface:SetPlayerIcon(head:GetChild("head"):GetChild("HeadIcon"), serverData.pic, head:GetChild("frame"), serverData.picFrame)
        if serverData.playerId == logicMgr.HeroManager.GetRoleId() then
            typeController.selectedIndex = 1;
        end
        --rank = serverData.rank or 0;
    end
    if rank <= 3 and rank > 0 then
        rankController.selectedIndex = rank - 1;
    else
        rankController.selectedIndex = 3;
        itemObj:GetChild("rank").text = rank;
    end
    if rank <= 0 then
        rankController.selectedIndex = 3;
        itemObj:GetChild("rank").text = getLanguage("NotInRank");
    else
        if isMe and rank > 100 then
            itemObj:GetChild("rank").text = getLanguage("NotInRank");
        else
            itemObj:GetChild("rank").text = rank;

        end
    end
end

function RankItem.getTableData(rank)
    for k, v in pairs(this.subRankTableDataList) do
        local rankCfg = decodeJsonStrToTabel(v.f_Rank)
        if rank >= rankCfg[1] and rank <= rankCfg[2] then
            return v
        end
    end
    return nil
end
function RankItem.ReceiveRankDataMsg()
    this.serverRankInfo = logicMgr.ActiveManager.GetTurntableRankInfo(this.activityId,this.rankType)
    this.updateData(this.rankType, this.timeCount)
end
function RankItem.OnDestroy()
    CloseEvent(Config.EventType.Fresh_Activity_Turntable_Rank,this.ReceiveRankDataMsg)
    this.DestroyRewardTimer();
end
function RankItem.DestroyRewardTimer()
    if this.rewardTimerId ~= nil then
        utimer.remove(this.rewardTimerId);
        this.rewardTimerId = nil;
    end
end
return RankItem;